package cn.le.netty.handler;

import cn.le.bean.enums.EnumMsgCode;
import cn.le.bean.vo.NettyMsg;
import cn.le.netty.cient.NettyClient;
import cn.le.netty.util.ConnectionUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * 客户端心跳发送
 */
public class HeartBeatReqHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception {
        //心跳响应
        NettyMsg msg = (NettyMsg) obj;
        if (msg.getCode() == EnumMsgCode.resp_heartbeat.getCode()){
            System.out.println(msg);
        }
        ctx.fireChannelRead(obj);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (!(evt instanceof IdleStateEvent)){
            super.userEventTriggered(ctx,evt);
            return;
        }
        IdleStateEvent event = (IdleStateEvent) evt;
        if (event.state().equals(IdleState.ALL_IDLE)){
            ctx.channel().close();//关闭链接,触发channelInactive
        }else if (event.state().equals(IdleState.READER_IDLE)){
            //发送心跳
            //ctx.writeAndFlush(NettyMsgUtils.getHeartBeat());
            System.out.println("-------------发送心跳--Heart Beat");
        }/*else event.state().equals(IdleState.WRITER_IDLE)){
           写超时这里不做处理,应为发送心跳时,就触发写操作
        }*/
    }
}
